package person.bing.fbcloud.auth.config;

import lombok.SneakyThrows;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author: mengfanbing
 * @date: 2019/7/5
 */
@Order(90)
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(proxyTargetClass = true, prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    @SneakyThrows
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()//表单登录
                .loginPage("/token/login")
                .loginProcessingUrl("/token/form")
                .successForwardUrl("/bing/testBing")
//                .successHandler(successEventHandler)
                .and()
                .logout().permitAll()
                .and()
                .httpBasic()//httpBasic登录
                .and()
                .authorizeRequests()
                .antMatchers(
                        "/oauth/token",
                        "/token/**",
                        "/actuator/**",
                        "/token/form",
                        "/forumuser"
                ).permitAll()
                .anyRequest().authenticated()//登录后其他接口都可以访问
                .and()
                .csrf().disable();//关闭跨域保护（解决post请求报403的问题）
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**");
    }
    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
    @Bean
    @SneakyThrows
    @Override
    public AuthenticationManager authenticationManagerBean(){
        return super.authenticationManagerBean();
    }

}

